<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xHTML1/DTD/xHTML1-transitional.dtd">
<HTML XMLns="http://www.w3.org/1999/xHTML" lang="utf8">
<head>
<title>test_trim</title>
<meta name="keywords" content="JS,事件冒泡,cancelBubble,stopPropagation" charset=utf-8/>
<!--[if !IE]> -->
  <script src="http://cdn.bootcss.com/jquery/2.2.0/jquery.min.js"></script>
  <!-- <![endif]-->
  <!--[if IE]>
      <script src="http://cdn.bootcss.com/jquery/1.12.0/jquery.js"></script>
  <![endif]-->
<style>
*{
  margin:0;
  padding:0;
}
</style>
</head>
<body>
<div>
  <input/>
  <button onclick="trimLeft()">左空格</button>
  <button onclick="trimRight()">有空格</button>
  <button onclick="trim()">左右空格</button>
</div>
<div id="result"></div> 
<script>
function trim(s){
  var tr = trimLeft(trimRight(s));
  return tr;
}

function trimLeft(s){
  var whitespace=new String(" \t\n\r");
  var tr=new String(s);
  var k=0;
  var j= tr.length;
  if(whitespace.indexOf(tr.charAt(0))!= -1){
    for (var i = 0; i <= j; i++) {
      if(whitespace.indexOf(tr.charAt(i))!= -1){
        k++;
      }
      else break;
    };
  }
  tr=tr.substring(k,j);
  return tr;
}

function trimRight(s){
  var whitespace = new String(" \t\n\r");
  var tr=new String(s);
  var k = tr.length;
  var j = tr.length;
  // console.log(j);
  if(whitespace.indexOf(tr.charAt(j-1))!= -1){
    for (var i = j-1; i >= 0; i--) {
      if(whitespace.indexOf(tr.charAt(i))!= -1){
        k--;
        // console.log(k);
      }
      else break;
    };
  }
  tr=tr.substring(0,k);
  return tr;

}

</script>
</body>
</HTML>
